#include "strconversion.h"

#include <QGroupBox>
#include <QHBoxLayout>
#include <QRegExpValidator>
#include <QDebug>

StrConversion::StrConversion(QWidget *parent)
    : QWidget(parent)
{
    initUi();
}

StrConversion::~StrConversion()
{

}

void StrConversion::initUi()
{
    m_firstEdit = new DTextEdit();
    m_secondEdit = new DTextEdit();

    DPushButton *firstPtn = new DPushButton("字符串转十六进制↓");
    DPushButton *secondPtn = new DPushButton("十六进制转字符串↑");

    QGroupBox *intGroup = new QGroupBox(this);
    intGroup->setTitle("字符串转换");
    intGroup->setGeometry(20, 20, 410, 510);

    QHBoxLayout *ptnLayout = new QHBoxLayout();
    ptnLayout->addWidget(firstPtn);
    ptnLayout->addWidget(secondPtn);
    ptnLayout->setSpacing(20);

    QVBoxLayout *mainLayout = new QVBoxLayout();
    mainLayout->addWidget(m_firstEdit);
    mainLayout->addLayout(ptnLayout);
    mainLayout->addWidget(m_secondEdit);
    mainLayout->setSpacing(10);

    intGroup->setLayout(mainLayout);

    connect(firstPtn, SIGNAL(clicked()), this, SLOT(slotStrToHex()));
    connect(secondPtn, SIGNAL(clicked()), this, SLOT(slotHexToStr()));
}

QString StrConversion::addSpace(QString str)
{
    int n = str.length();
    while(n-2 > 0)
    {
        n = n - 2;
        str.insert(n," ");
    }

    return str;
}

void StrConversion::slotStrToHex()
{
    QString str = m_firstEdit->toPlainText();
    QByteArray byte = str.toLatin1();

    m_secondEdit->setText(addSpace(byte.toHex()));
}

void StrConversion::slotHexToStr()
{
    QString str = m_secondEdit->toPlainText().remove(QRegExp(" "));
    QByteArray byte = QByteArray::fromHex(str.toLatin1());

    m_firstEdit->setText(byte.data());
}
